package me.zxk.smartagriculture.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import me.zxk.smartagriculture.common.ApiResponse;
import me.zxk.smartagriculture.dto.user.*;
import me.zxk.smartagriculture.service.UserService;
import me.zxk.smartagriculture.service.FileUploadService;
import me.zxk.smartagriculture.util.JwtUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 用户控制器
 */
@Tag(name = "用户管理", description = "用户信息管理、头像上传、密码修改等API")
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
@SecurityRequirement(name = "bearerAuth")
public class UserController {

    private final UserService userService;
    private final FileUploadService fileUploadService;
    private final JwtUtil jwtUtil;

    /**
     * 获取当前用户信息
     */
    @Operation(summary = "获取当前用户信息", description = "获取当前登录用户的详细信息")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "查询成功",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "500",
                    description = "服务器内部错误",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
    })
    @GetMapping("/me")
    public ApiResponse<UserInfoResponse> getCurrentUserInfo(HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            UserInfoResponse response = userService.getUserInfo(userId);
            return ApiResponse.success(response);
        } catch (Exception e) {
            return ApiResponse.error(500, e.getMessage());
        }
    }

    /**
     * 更新当前用户信息
     */
    @Operation(summary = "更新当前用户信息", description = "更新当前登录用户的基本信息，如昵称、邮箱等")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "更新成功",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "400",
                    description = "更新失败，参数错误或数据验证失败",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
    })
    @PutMapping("/me")
    public ApiResponse<UserInfoResponse> updateCurrentUserInfo(
            @Parameter(description = "用户信息更新请求", required = true) @Valid @RequestBody UpdateUserRequest request,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromRequest(httpRequest);
            UserInfoResponse response = userService.updateUserInfo(userId, request);
            return ApiResponse.success(response);
        } catch (Exception e) {
            return ApiResponse.error(400, e.getMessage());
        }
    }

    /**
     * 上传用户头像
     */
    @Operation(summary = "上传用户头像", description = "上传并更新当前用户的头像图片")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "头像上传成功",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "400",
                    description = "上传失败，文件格式不支持或文件过大",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
    })
    @PostMapping("/me/avatar")
    public ApiResponse<String> uploadAvatar(
            @Parameter(description = "头像文件，支持jpg、png格式", required = true) @RequestParam("avatarFile") MultipartFile file,
            HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            // 上传文件并获取文件URL
            String avatarUrl = fileUploadService.uploadAvatar(file, userId);
            // 更新用户数据库中的头像URL
            userService.updateUserAvatar(userId, avatarUrl);
            return ApiResponse.success("头像更新成功", avatarUrl);
        } catch (Exception e) {
            return ApiResponse.error(400, e.getMessage());
        }
    }

    /**
     * 修改密码
     */
    @Operation(summary = "修改密码", description = "修改当前用户的登录密码")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "密码修改成功",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "400",
                    description = "修改失败，原密码错误或新密码不符合要求",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
    })
    @PostMapping("/me/change-password")
    public ApiResponse<Void> changePassword(
            @Parameter(description = "密码修改请求信息", required = true) @Valid @RequestBody ChangePasswordRequest request,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromRequest(httpRequest);
            userService.changePassword(userId, request);
            return ApiResponse.success("密码修改成功", null);
        } catch (Exception e) {
            return ApiResponse.error(400, e.getMessage());
        }
    }

    /**
     * 删除当前用户账户
     */
    @Operation(summary = "删除当前用户账户", description = "注销当前用户账户，删除所有相关数据")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "账户注销成功",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "500",
                    description = "服务器内部错误",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
    })
    @DeleteMapping("/me")
    public ApiResponse<Void> deleteCurrentUser(HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            userService.deleteUser(userId);
            return ApiResponse.success("账户注销成功", null);
        } catch (Exception e) {
            return ApiResponse.error(500, e.getMessage());
        }
    }

//    /**
//     * 获取用户设置
//     */
//    @Operation(summary = "获取用户设置", description = "获取当前用户的个人设置信息")
//    @ApiResponses(value = {
//            @io.swagger.v3.oas.annotations.responses.ApiResponse(
//                    responseCode = "200",
//                    description = "查询成功",
//                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
//            @io.swagger.v3.oas.annotations.responses.ApiResponse(
//                    responseCode = "500",
//                    description = "服务器内部错误",
//                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
//    })
//    @GetMapping("/me/settings")
//    public ApiResponse<UserSettingsResponse> getUserSettings(HttpServletRequest request) {
//        try {
//            Long userId = getUserIdFromRequest(request);
//            UserSettingsResponse response = userService.getUserSettings(userId);
//            return ApiResponse.success(response);
//        } catch (Exception e) {
//            return ApiResponse.error(500, e.getMessage());
//        }
//    }
//
//    /**
//     * 更新用户设置
//     */
//    @Operation(summary = "更新用户设置", description = "更新当前用户的个人设置信息")
//    @ApiResponses(value = {
//            @io.swagger.v3.oas.annotations.responses.ApiResponse(
//                    responseCode = "200",
//                    description = "设置更新成功",
//                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
//            @io.swagger.v3.oas.annotations.responses.ApiResponse(
//                    responseCode = "400",
//                    description = "更新失败，参数错误或数据验证失败",
//                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
//    })
//    @PutMapping("/me/settings")
//    public ApiResponse<UserSettingsResponse> updateUserSettings(
//            @Parameter(description = "用户设置更新请求信息", required = true) @Valid @RequestBody UpdateUserSettingsRequest request,
//            HttpServletRequest httpRequest) {
//        try {
//            Long userId = getUserIdFromRequest(httpRequest);
//            UserSettingsResponse response = userService.updateUserSettings(userId, request);
//            return ApiResponse.success(response);
//        } catch (Exception e) {
//            return ApiResponse.error(400, e.getMessage());
//        }
//    }

    /**
     * 从请求中获取用户ID
     */
    private Long getUserIdFromRequest(HttpServletRequest request) {
        String token = extractTokenFromRequest(request);
        return jwtUtil.getUserIdFromToken(token);
    }

    /**
     * 从请求中提取JWT Token
     */
    private String extractTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        throw new RuntimeException("Token not found");
    }
}
